package net.qhzw.vip.qiyu.util;

import net.qhzw.vip.qiyu.handler.ApiException;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 中文转大写评语
 */
public class PinyinUtils {


//    public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {
//        System.out.println(testPinyin("张生仓"));
//    }

    /***
     * 获取中文的大写拼音
     * @param name
     * @throws BadHanyuPinyinOutputFormatCombination
     */
    public static String toPinyin(String name) {
        try {
            char[] charArray = name.toCharArray();
            StringBuilder pinyin = new StringBuilder();
            HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
            //设置大小写格式
            defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
            //设置声调格式：
            defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            for (int i = 0; i < charArray.length; i++) {
                //匹配中文,非中文转换会转换成null
                if (Character.toString(charArray[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(charArray[i], defaultFormat);
                    String string = hanyuPinyinStringArray[0];
                    pinyin.append(string);
                } else {
                    pinyin.append(charArray[i]);
                }
            }
            return pinyin.toString();
        } catch (Exception e) {
            throw new ApiException(e.getMessage());
        }
    }


}
